package utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class HttpRequestClient {

    public static String get(String url) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);

        String resp = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            resp = IOUtils.toString(response.getEntity().getContent(), Charset.forName("utf-8"));
            log.debug(String.format("[GET]请求地址:%s \r\n响应结果：%s", url, resp));
        } catch (Exception e) {
            String errMsg = e.getClass().getName() + " : " + e.getMessage();
            log.error(String.format("[GET]请求地址:%s \r\n异常信息：%s", url, errMsg));
            throw e;
        } finally {
            //释放资源
            httpGet.releaseConnection();
        }

        return resp;
    }

    public static String post(String uri, String params) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(uri);

        List<NameValuePair> valuePairs = new ArrayList<>();
        valuePairs.add(new BasicNameValuePair("params", params));
        httpPost.setEntity(new UrlEncodedFormEntity(valuePairs,"utf-8"));

        String resp = null;
        try {
            HttpResponse response = httpClient.execute(httpPost);
            resp = IOUtils.toString(response.getEntity().getContent(), Charset.forName("utf-8"));
            log.info(String.format("[POST]请求地址:%s \r\n请求参数:%s \r\n响应结果：%s", uri, params, resp));
        } catch (Exception e) {
            String errMsg = e.getClass().getName() + " : " + e.getMessage();
            log.error(String.format("[POST]请求地址:%s \r\n请求参数:%s \r\n 异常信息：%s", uri, params, errMsg));
            throw e;
        } finally {
            //释放资源
            httpPost.releaseConnection();
        }

        return resp;
    }

}
